package logic

import (
	"context"
	"errors"
	"mei-admin/models/cache"
	"mei-admin/models/mysql"
	"mei-admin/pkg"

	"mei-admin/meirpc/internal/svc"
	"mei-admin/meirpc/meirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *meirpc.RegisterRequest) (*meirpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.MeiUser
	mysql.DB.Debug().Where("account = ?" + in.Account).Find(&user)

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if in.Captcha != result {
		return nil, errors.New("图形验证码错误")
	}

	s, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if in.SendSms != s {
		return nil, errors.New("短信验证码错误")
	}

	users := mysql.MeiUser{
		Account:  in.Account,
		Password: pkg.Md5str(in.Password),
	}
	mysql.DB.Debug().Create(&users)

	return &meirpc.RegisterResponse{
		UserId: int64(users.ID),
	}, nil
}
